﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace BUGCOME.Infrastructure.Helper
{
    public static class EncryptHelper
    {
        /// <summary>
        /// 生成包含大小写字母和数字的SHA-256哈希，基于secretKey动态调整转换规则
        /// </summary>
        /// <param name="input">原始字符串</param>
        /// <param name="secretKey">用于自定义转换规则的密钥</param>
        /// <returns>混合大小写的SHA-256结果</returns>
        public static string Sha256WithMixedCase(string input, string secretKey = "CAE9B237")
        {
            if (string.IsNullOrEmpty(input))
                return string.Empty;

            // 1. 生成标准SHA-256（大写字母+数字）
            string originalSha256 = ComputeSha256Hash(input);
            char[] chars = originalSha256.ToCharArray();

            // 2. 从secretKey提取配置信息（数字部分）
            var keyDigits = secretKey.Where(c => char.IsDigit(c)).Select(c => c - '0').ToList();
            if (keyDigits.Count == 0)
            {
                // 若secretKey无数字，使用默认规则（偶数索引转小写）
                return ApplyDefaultRule(chars);
            }

            // 3. 根据secretKey第一个数字决定基础转换规则
            int baseRule = keyDigits[0] % 2; // 0-偶数规则，1-奇数规则
            ApplyBaseRule(chars, baseRule);

            // 4. 根据secretKey后续数字进行二次大小写反转
            ApplySecondaryRule(chars, keyDigits.Skip(1).ToList());

            return new string(chars);
        }

        /// <summary>
        /// 计算字符串的SHA-256哈希值
        /// </summary>
        /// <param name="input">输入字符串</param>
        /// <returns>大写的SHA-256哈希字符串</returns>
        private static string ComputeSha256Hash(string input)
        {
            // 创建SHA-256实例
            using (SHA256 sha256Hash = SHA256.Create())
            {
                // 将输入字符串转换为字节数组
                byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

                // 将字节数组转换为十六进制字符串
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < bytes.Length; i++)
                {
                    builder.Append(bytes[i].ToString("X2")); // X2确保两位数的十六进制表示
                }
                return builder.ToString();
            }
        }

        /// <summary>
        /// 应用默认转换规则（偶数索引转小写）
        /// </summary>
        private static string ApplyDefaultRule(char[] chars)
        {
            for (int i = 0; i < chars.Length; i++)
            {
                if (i % 2 == 0 && chars[i] >= 'A' && chars[i] <= 'F')
                {
                    chars[i] = char.ToLower(chars[i]);
                }
            }
            return new string(chars);
        }

        /// <summary>
        /// 应用基础转换规则
        /// </summary>
        /// <param name="chars">SHA-256字符数组</param>
        /// <param name="baseRule">0-偶数索引转小写，1-奇数索引转小写</param>
        private static void ApplyBaseRule(char[] chars, int baseRule)
        {
            for (int i = 0; i < chars.Length; i++)
            {
                bool shouldConvert = (baseRule == 0 && i % 2 == 0) || (baseRule == 1 && i % 2 == 1);
                if (shouldConvert && chars[i] >= 'A' && chars[i] <= 'F')
                {
                    chars[i] = char.ToLower(chars[i]);
                }
            }
        }

        /// <summary>
        /// 应用二次转换规则（根据指定索引反转大小写）
        /// </summary>
        /// <param name="chars">SHA-256字符数组</param>
        /// <param name="indices">需要反转大小写的索引列表</param>
        private static void ApplySecondaryRule(char[] chars, List<int> indices)
        {
            foreach (int index in indices)
            {
                // SHA-256哈希长度为64个字符，索引范围0-63
                if (index < 0 || index >= chars.Length) continue;

                char c = chars[index];
                if (c >= 'a' && c <= 'f')
                {
                    chars[index] = char.ToUpper(c);
                }
                else if (c >= 'A' && c <= 'F')
                {
                    chars[index] = char.ToLower(c);
                }
                // 数字不做处理
            }
        }
    }
}
